use common_base::{once_cell::sync::Lazy, sqlx::mysql::MySqlArguments};
use common_core::{data::DatasetUtil, ServiceContextBase};

pub struct MetadataUtil;

impl MetadataUtil {
    const MLANG_METATABLE: Lazy<Vec<&'static str>> = Lazy::new(|| {
        vec![
            "SYS_OBJECTS",
            "SYS_OBJCOLS",
            "SYS_DICTS",
            "SYS_FACTS",
            "SYS_MODEL",
            "SYS_MDL_CTN",
        ]
    });
}

impl MetadataUtil {
    pub fn generate_sql_and_args(
        srv_ctx: &ServiceContextBase,
        meta_table: &str,
        fields: &str,
        where_: &str,
        orderby: &str,
        arguments: MySqlArguments,
        object_id: &str,
    ) -> (String, MySqlArguments) {
        if Self::is_multi_lang_aware(object_id) {
            Self::generate_metadata_sql_and_args(
                srv_ctx, meta_table, fields, where_, orderby, arguments, true,
            )
        } else {
            DatasetUtil::generate_sql_and_args(
                srv_ctx, meta_table, fields, where_, orderby, arguments,
            )
        }
    }

    #[inline]
    fn is_multi_lang_aware(object_id: &str) -> bool {
        !Self::MLANG_METATABLE.contains(&object_id)
    }

    fn generate_metadata_sql_and_args(
        srv_ctx: &ServiceContextBase,
        meta_table: &str,
        fields: &str,
        where_: &str,
        orderby: &str,
        arguments: MySqlArguments,
        sys_col_multi_lang: bool,
    ) -> (String, MySqlArguments) {
        // multi language setting
        let mut f_lang = srv_ctx.get_value_by_env_name("Language").to_owned();
        if f_lang.is_empty() {
            let i18n = srv_ctx.get_value_by_env_name("International");
            let country = srv_ctx.get_value_by_env_name("Country");
            if !i18n.is_empty() && !country.is_empty() {
                f_lang = format!("{}_{}", i18n, country);
            }
        }

        if !f_lang.is_empty() {
            if srv_ctx.get_value_by_param_name("isFromClient").eq("1") {
                todo!()
            } else if srv_ctx
                .get_value_by_param_name("META_LOAD_TYPE")
                .eq("LOAD4NEED")
            {
                todo!()
            } else {
                todo!()
            }
        } else {
            DatasetUtil::generate_sql_and_args(
                srv_ctx, meta_table, fields, where_, orderby, arguments,
            )
        }
    }
}
